<?php


namespace Ffzhou\HydrophisLogin\Api\Controller;


use Flarum\Api\Controller\AbstractShowController;
use Flarum\Api\Serializer\CurrentUserSerializer;
use Flarum\Locale\Translator;
use Flarum\User\Exception\NotAuthenticatedException;
use Flarum\User\User;
use Flarum\User\UserValidator;
use InvalidArgumentException;
use Illuminate\Support\Arr;
use Psr\Http\Message\ServerRequestInterface as Request;
use Tobscure\JsonApi\Document;

class ChangeUsernameController extends AbstractShowController
{
    /**
     * {@inheritdoc}
     */
    public $serializer = CurrentUserSerializer::class;

    /**
     * @var Translator
     */
    private $translator;

    /**
     * @var UserValidator
     */
    private $validator;

    /**
     * @param Dispatcher $bus
     */
    public function __construct(Translator $translator, UserValidator $validator)
    {
        $this->translator = $translator;
        $this->validator = $validator;
    }

    /**
     * {@inheritdoc}
     */
    public function data(Request $request, Document $document)
    {
        $actor = $request->getAttribute('actor');
        $body = $request->getParsedBody();
        $username = trim(Arr::get($body, 'username', ''));
        // 判断用户身份
        if ($actor->isGuest()) {
            throw new NotAuthenticatedException;
        }


        // 修改用户名
        $actor->rename($username);

        // 验证器
        $this->validator->setUser($actor);
        $this->validator->assertValid(array_merge($actor->getDirty()));

        // 存储用户信息
        $actor->save();
        return $actor;
    }
}
